package il.technion.cs236369.webserver.simpleServlets;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import il.technion.cs236369.webserver.components.ServerUtils;
import il.technion.cs236369.webserver.components.WebRequest;

import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.util.EntityUtils;

public class UserDistanceServlet implements ISimpleServlet {

	
	private Map<String, UserDistanceSession> id2session = new ConcurrentHashMap<String, UserDistanceSession>();
	
	@Override
	public HttpResponse HandleRequest(WebRequest wRequest) {
		// TODO Auto-generated method stub
		try {
			HttpRequest hReq = wRequest.getHttpRequest();
			if (hReq.getRequestLine().getMethod().toUpperCase() =="POST") return HandlePostRequest(wRequest);
			if (hReq.getRequestLine().getMethod().toUpperCase() =="GET") return HandleGetRequest(wRequest);
			throw new Exception("not supported operation. try post or get.");
		} catch (Exception e) {
			HttpResponse resp = ServerUtils.getBasicHtmlResponse(HttpStatus.SC_BAD_REQUEST, e.getMessage());
			ServerUtils.sendResponseToClient(wRequest.getClientConnection(), resp);
		}

		return null;
	}

	private HttpResponse HandleGetRequest(WebRequest wRequest) {
		return null;//TODO
	}
	
	
	
	private HttpResponse HandlePostRequest(WebRequest wRequest) throws Exception {
		
		if (!(wRequest.getHttpRequest() instanceof HttpEntityEnclosingRequest)){
			throw new Exception(
					"Post operation should include a geographic coordinate in body.");
		}

		HttpEntityEnclosingRequest hReq = (HttpEntityEnclosingRequest) wRequest.getHttpRequest();
		HttpEntity entity = hReq.getEntity();
		
		try {
			
			
			GeoCoordinate coordinates = new GeoCoordinate(EntityUtils.toString(entity));
			
			
		
		
		
		} catch (ParseException | IOException e) {
			// error parsing double.
			ServerUtils.sendInternalServerError(wRequest
					.getClientConnection());
			throw new Exception("coordinate parsing error. coordinates should be writen with number only.");
		}
		return null;
	}
	
	

}
